import { defineStore } from 'pinia'

// 订单状态管理
export const useOrderStore = defineStore('order', {
  state: () => ({
    orders: [], // 订单列表
    currentOrder: null, // 当前查看的订单详情
    checkoutInfo: {
      address: null, // 选中的收货地址
      paymentMethod: 'alipay', // 支付方式：alipay, wechat, bank
      couponId: null, // 优惠券ID
      remark: '' // 订单备注
    },
    paymentStatus: 'idle' // 支付状态：idle, processing, success, failed
  }),
  getters: {
    // 获取待付款订单
    pendingOrders: (state) => {
      return state.orders.filter(order => order.status === 'pending')
    },
    // 获取待发货订单
    processingOrders: (state) => {
      return state.orders.filter(order => order.status === 'processing')
    },
    // 获取待收货订单
    shippedOrders: (state) => {
      return state.orders.filter(order => order.status === 'shipped')
    },
    // 获取已完成订单
    completedOrders: (state) => {
      return state.orders.filter(order => order.status === 'completed')
    },
    // 获取已取消订单
    cancelledOrders: (state) => {
      return state.orders.filter(order => order.status === 'cancelled')
    },
    // 获取退款中订单
    refundingOrders: (state) => {
      return state.orders.filter(order => order.status === 'refunding')
    },
    // 获取已退款订单
    refundedOrders: (state) => {
      return state.orders.filter(order => order.status === 'refunded')
    }
  },
  actions: {
    // 设置订单列表
    setOrders(orders) {
      this.orders = orders
    },
    
    // 添加新订单
    addOrder(order) {
      this.orders.unshift(order)
    },
    
    // 更新订单状态
    updateOrderStatus(orderId, status) {
      const order = this.orders.find(order => order.id === orderId)
      if (order) {
        order.status = status
      }
    },
    
    // 设置当前订单详情
    setCurrentOrder(order) {
      this.currentOrder = order
    },
    
    // 清空当前订单详情
    clearCurrentOrder() {
      this.currentOrder = null
    },
    
    // 设置结算信息
    setCheckoutInfo(info) {
      this.checkoutInfo = {
        ...this.checkoutInfo,
        ...info
      }
    },
    
    // 清空结算信息
    clearCheckoutInfo() {
      this.checkoutInfo = {
        address: null,
        paymentMethod: 'alipay',
        couponId: null,
        remark: ''
      }
    },
    
    // 设置支付状态
    setPaymentStatus(status) {
      this.paymentStatus = status
    },
    
    // 提交订单（模拟）
    async submitOrder(cartItems) {
      try {
        this.setPaymentStatus('processing')
        // 这里应该调用后端API提交订单
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 模拟生成订单数据
        const orderId = 'ORD' + Date.now() + Math.floor(Math.random() * 1000)
        const totalAmount = cartItems.reduce((total, item) => {
          return total + item.price * item.quantity
        }, 0)
        
        const newOrder = {
          id: orderId,
          items: cartItems,
          totalAmount,
          status: 'pending',
          createTime: new Date().toISOString(),
          address: this.checkoutInfo.address,
          paymentMethod: this.checkoutInfo.paymentMethod,
          remark: this.checkoutInfo.remark
        }
        
        this.addOrder(newOrder)
        this.setCurrentOrder(newOrder)
        this.setPaymentStatus('success')
        
        return { success: true, orderId }
      } catch (error) {
        console.error('提交订单失败:', error)
        this.setPaymentStatus('failed')
        return { success: false, message: '提交订单失败，请重试' }
      }
    },
    
    // 取消订单
    async cancelOrder(orderId) {
      try {
        // 这里应该调用后端API取消订单
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        this.updateOrderStatus(orderId, 'cancelled')
        return { success: true }
      } catch (error) {
        console.error('取消订单失败:', error)
        return { success: false, message: '取消订单失败，请重试' }
      }
    },
    
    // 确认收货
    async confirmReceipt(orderId) {
      try {
        // 这里应该调用后端API确认收货
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        this.updateOrderStatus(orderId, 'completed')
        return { success: true }
      } catch (error) {
        console.error('确认收货失败:', error)
        return { success: false, message: '确认收货失败，请重试' }
      }
    },
    
    // 申请退款
    async applyRefund(orderId, reason) {
      try {
        // 这里应该调用后端API申请退款
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        this.updateOrderStatus(orderId, 'refunding')
        return { success: true }
      } catch (error) {
        console.error('申请退款失败:', error)
        return { success: false, message: '申请退款失败，请重试' }
      }
    }
  },
  // 持久化配置
  persist: {
    key: 'ai-shop-order',
    storage: localStorage,
    paths: ['orders', 'checkoutInfo']
  }
})